package com.leps.nq.bu.controller;

import cn.hutool.core.util.StrUtil;
import com.leps.nq.bu.entity.BuCust;
import com.leps.nq.bu.service.IBuCustService;
import com.leps.nq.bu.vo.CustQueryModel;
import com.leps.nq.bu.vo.CustVo;
import com.leps.nq.common.aspect.Log;
import com.leps.nq.common.enums.BusinessType;
import com.leps.nq.common.vo.PageVo;
import com.leps.nq.common.vo.R;
import com.leps.nq.common.vo.RBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 客户表 前端控制器
 * </p>
 *
 * @author hex
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/bu/bu-cust")
@Api(tags = "客户管理")
public class BuCustController {
    @Autowired
    private IBuCustService custService;

    @GetMapping("/forSelect")
    @ApiOperation("客户下拉列表")
    public R<List<BuCust>> listForSelect() {
        List<BuCust> list = this.custService.listForSelect();
        return RBuilder.ok(list);
    }

    @GetMapping
    @ApiOperation("客户列表")
    public R<PageVo<CustVo>> list(CustQueryModel custQueryModel) {
        PageVo<CustVo> pageVo = this.custService.pageByQueryModel(custQueryModel);
        return RBuilder.ok(pageVo);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询客户信息")
    public R<BuCust> getById(@PathVariable Integer id) {
        return RBuilder.ok(this.custService.getById(id));
    }

    @PostMapping
    @ApiOperation("添加客户")
    @Log(title = "客户", businessType = BusinessType.INSERT)
    public R<?> save(@RequestBody BuCust cust) {
        String custName = cust.getCustName();
        Long count = this.custService.lambdaQuery().eq(BuCust::getCustName, custName).count();
        if (count > 0) {
            String msg = StrUtil.format("系统中已存在 [ {} ] 这个客户，请不要重复添加。", custName);
            throw new RuntimeException(msg);
        }
        boolean success = this.custService.save(cust);
        return RBuilder.ofBoolean(success);
    }

    @PutMapping
    @ApiOperation("更新客户")
    @Log(title = "客户", businessType = BusinessType.UPDATE)
    public R<?> update(@RequestBody BuCust cust) {
        boolean b = this.custService.updateById(cust);
        return RBuilder.ofBoolean(b);
    }

    @DeleteMapping
    @ApiOperation("删除客户")
    @Log(title = "客户", businessType = BusinessType.DELETE)
    public R<?> remove(@RequestBody List<Integer> custIds) {
        boolean b = this.custService.removeBatchByIds(custIds);
        return RBuilder.ofBoolean(b);
    }
}
